#ifndef NET_H
#define NET_H

#include <QObject>
#include <QByteArray>
#include <QDateTime>
#include <QList>
#include <QTime>

#include <QStringList>
#include <QVariantList>
#include <QByteArray>

#include <QTcpServer>
#include <QTcpSocket>

struct log_event
{
	bool valid;

	QDateTime current_time;
	QString str_current_time;
	QString client_name;

	quint8 msg_version;
	quint8 unicode;
	QString server_name;
	QString logger_name;
	int log_level;
	QString NDC;
	QString message;
	QString thread;
	int sec;
	int usec;
	QString file;
	int line;
	QString func;

	QByteArray vl2ba(QVariantList vl);
	QVariantList ba2vl(QByteArray ba);

	QByteArray to_ba();
	bool from_ba(QByteArray ba);

	log_event()
	{
		valid = false;
	}
};

Q_DECLARE_METATYPE(log_event)

struct net_client
{
	QString name;
	QTcpSocket *socket;
	QByteArray data;
	int rem; // remaining bytes to read

	net_client()
	{
		name = "";
		socket = NULL;
		data.clear();
		rem = 0;
	}
};

class net : public QObject
{
	Q_OBJECT
public:
	explicit net(QObject *parent = 0);

	static QByteArray int2ba(quint32 value);
	static quint32 ba2int(QByteArray ba, int offset);

signals:
	void packet_full(log_event le);
	void new_client(QString client_name);

public slots:
	void start_server(quint16 port);

private slots:
	void slot_client_connected();
	void slot_ready_read();

private:
	bool ready;
	QTcpServer server;
	QList<net_client*> clients;
	net_client* get_client(QTcpSocket *s);

	bool process_packet(QString client, QByteArray data);
	QString get_string(QByteArray data, int &offset);
	int get_int(QByteArray data, int &offset);
};

#endif // NET_H
